<template>
	<view class="percard">
		<canvas v-show='isshow' canvas-id="myCanvas" :style="{ width: canvasWidth, height: canvasHeight }"></canvas>
		<image v-show='!isshow' @longtap="saveImage()" :src="imgs" mode=""
			:style="{ width: canvasWidth, height: canvasHeight }"></image>
		<uni-popup ref="popup" type="center">
			<view class="pop1">
				<view class="tit">
					<!-- 点击下面按钮下载到相册 -->
					请长按下载图片
				</view>
				<!-- <view class="btns" @click="saveImage()">点击保存</view> -->
				<view class="btns" @click="closer()">知道了</view>
				<view class="btns" @click="goindex()">回到上一页</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			isshow: true,
			formData: {
				avatar: '',
				nickname: '',
				id: '',
				openid: '',
				unionid: '',
				distributionCode: '',

			},
			myObj: {
				headImg: '',
				name: '', //微信昵称
				introduce: '', //uid
				introduction: '个性签名：喝好酒到酒华仕，是好酒进酒华仕!',
				bgImg: 'https://web.jiuhuashi.cn/uploads/poster/red-package.png', //背景图
				rwmImg: '',
				smText: '长按识别二维码' //个性签名
			},
			canvasWidth: 375, //画布宽度
			canvasHeight: 800, //画布高度
			ratio: 0, //计算UI设计稿和你手机的屏幕宽度比例（例如UI设计稿是750宽度 你手机是350宽度 比例就是2  那么你画布画图时候 所有的尺寸大小、宽高、位置、定位左右上下都需要除以 / 比例2 ）
			widths: '',
			heights: '',
			imgs: ''

		}
	},
	watch: {
		imgs(newlue) {
			if (newlue) {
				this.isshow = false
				this.$refs.popup.open()
			}
		}
	},
	computed: {},
	onLoad() {
		let that = this
		uni.getSystemInfo({
			success: res => {
				console.log(res);
				// res.screenWidth 设备宽度
				that.canvasWidth = res.screenWidth + 'px'
				that.widths = res.screenWidth
				that.ratio = 750 / res.screenWidth
				that.canvasHeight = (that.widths / 375) * 800 + 'px'
				that.heights = (that.widths / 375) * 800
			}
		})
		uni.showLoading({
			title: '海报生成中...'
		});
		this.fetchData();
		// that.downImgUrl()
	},
	methods: {
		fetchData() {
			uni.showLoading({
				mask: true,
				title: '用户信息获取中...'
			})
			let getData = async () => {
				let getUserInfo = await new Promise((resolve, reject) => {
					this.$api.baseInfo.getUserInfo().then(res => {
						console.log(res);
						uni.hideLoading();
						this.formData.avatar = res.data.avatar;
						this.formData.id = res.data.id;
						this.formData.nickname = res.data.nickname;
						this.formData.distributionCode = res.data.distribution_code;
						resolve(this.formData);
					})
				})

				let qrCodeUrl = await new Promise((resolve, reject) => {
					this.$api.baseInfo.getMnQrcode(this.formData.distributionCode).then(res => {
						resolve(res.data.qr_code);
					})
				})
				console.log(getUserInfo);
				this.myObj.headImg = this.formData.avatar;
				this.myObj.name = this.formData.nickname;
				this.myObj.introduce = 'UID:' + this.formData.id;
				this.myObj.rwmImg = qrCodeUrl;
				this.downImgUrl();
			}
			getData();
		},
		downImgUrl() {
			let that = this;
			uni.getImageInfo({
				src: that.myObj.headImg,
				success: function (res) {
					that.myObj.headImg = res.path
					uni.getImageInfo({
						src: that.myObj.bgImg,
						success: function (res) {
							that.myObj.bgImg = res.path
							uni.getImageInfo({
								src: that.myObj.rwmImg,
								success: function (res) {
									that.myObj.rwmImg = res.path
									that.drawPageImg()
								}
							});
						}
					});
				}
			});

		},
		closer() {
			this.$refs.popup.close()
		},
		goindex() {
			uni.navigateBack({
				delta: 1
			})
		},
		saveImage() {
			uni.saveImageToPhotosAlbum({
				filePath: this.imgs,
				success: function () {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: "已保存到系统相册",
					})
				},
				fail: function (error) {
					uni.showModal({
						title: '提示',
						content: '若点击不授权，将无法使用保存图片功能',
						cancelText: '不授权',
						cancelColor: '#999',
						confirmText: '授权',
						confirmColor: '#f94218',
						success(res) {
							console.log(res)
							if (res.confirm) {
								// 选择弹框内授权
								uni.openSetting({
									success(res) {
										console.log(res.authSetting)
									}
								})
							} else if (res.cancel) {
								// 选择弹框内 不授权
								console.log('用户点击不授权')
							}
						}
					})
				}
			})
		},
		//画一个带圆角矩形
		ctxCircular(ctx, img, x, y, width, height, r, shadow) {
			ctx.beginPath() //开始绘制
			ctx.save() //保存(canvas)状态
			ctx.moveTo(x + r, y)
			ctx.lineTo(x + width - r, y)
			ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
			ctx.lineTo(x + width, y + height - r)
			ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * 0.5)
			ctx.lineTo(x + r, y + height)
			ctx.arc(x + r, y + height - r, r, Math.PI * 0.5, Math.PI)
			ctx.lineTo(x, y + r)
			ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
			if (shadow == 1) {
				ctx.shadowBlur = 20; // 模糊效果程度的
				ctx.shadowColor = 'red'; // 阴影颜色
			}
			ctx.fill() //对当前路径中的内容进行填充
			ctx.clip() //从原始画布中剪切任意形状和尺寸
			ctx.closePath() //关闭一个路径
			ctx.drawImage(img, x, y, width, height);
			ctx.restore() //恢复(canvas)状态
		},
		//画一个矩形也就是整个海报的背景
		ctxRectangle(ctx, x, y, width, height, r, gnt) {
			ctx.beginPath()
			ctx.save() //保存状态
			ctx.moveTo(x + r, y)
			ctx.lineTo(x + width - r, y)
			ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
			ctx.lineTo(x + width, y + height - r)
			ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * 0.5)
			ctx.lineTo(x + r, y + height)
			ctx.arc(x + r, y + height - r, r, Math.PI * 0.5, Math.PI)
			ctx.lineTo(x, y + r)
			ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
			ctx.fillStyle = gnt
			ctx.fill() //对当前路径中的内容进行填充
			ctx.closePath() //关闭一个路径
		},
		ctxText(ctx, textFont, textAlign, textFillStyle, textName, x, y) {
			ctx.beginPath()
			ctx.save() //保存状态
			//字体
			ctx.font = textFont,
				//字体样式
				ctx.textAlign = textAlign
			//字体颜色
			ctx.fillStyle = textFillStyle
			//填充字体
			ctx.fillText(textName, x, y)
		},
		ctxTextWrap(ctx, text, x, y, w) {
			//自动换行介绍
			var temp = ""
			var row = []
			let gxqm = ''
			if (text) {
				gxqm = text
			} else {
				gxqm = '未设置个性签名'
			}
			let gexingqianming = gxqm.split("")
			for (var a = 0; a < gexingqianming.length; a++) {
				if (ctx.measureText(temp).width < w) { } else {
					row.push(temp)
					temp = ""
				}
				temp += gexingqianming[a]
			}
			row.push(temp)
			ctx.font = "13px arail"
			ctx.textAlign = 'left';
			ctx.fillStyle = "#000000"
			for (var b = 0; b < row.length; b++) {
				ctx.fillText(row[b], x, y + (b + 1) * 20)
			}
		},
		// 使用画布绘制页面
		drawPageImg() {
			let _this = this
			// 生成画布
			const ctx = uni.createCanvasContext('myCanvas')
			// 绘制背景
			const bcg = ctx.createLinearGradient(0, 0, 0, _this.heights)
			bcg.addColorStop(0.4, '#D9EBE6')
			bcg.addColorStop(1, '#fff')
			_this.ctxRectangle(ctx, 0, 0, (_this.widths), (_this.heights), 0, bcg)
			//名字
			_this.ctxText(ctx,
				'normal bold 18px Arial,PingFang SC',
				'left',
				'#00663A',
				_this.myObj.name, 220 / _this.ratio, 128 / _this.ratio)
			//名称
			_this.ctxText(ctx,
				'13px Arial,PingFang SC',
				'left',
				'#242424',
				_this.myObj.introduce, 220 / _this.ratio, 170 / _this.ratio)
			//介绍
			_this.ctxTextWrap(ctx, _this.myObj.introduction, 220 / _this.ratio, 170 / _this.ratio, 460 / _this.ratio)
			// // 背景图
			ctx.drawImage(_this.myObj.bgImg, //图像资源
				(48 / _this.ratio),//图像的左上角在目标canvas上 X 轴的位置
				(290 / _this.ratio),//图像的左上角在目标canvas上 Y 轴的位置
				(660 / _this.ratio),//在目标画布上绘制图像的宽度
				(814 / _this.ratio)//在目标画布上绘制图像的高度
			)
			_this.ctxText(ctx,
				'13px Arial,PingFang SC',
				'center',
				'#242424',
				_this.myObj.smText, 375 / _this.ratio, 1390 / _this.ratio)
			// // 绘制头像
			_this.ctxCircular(ctx, _this.myObj.headImg, (40 / _this.ratio), (100 / _this.ratio), (160 / _this.ratio), (
				160 / _this.ratio), 80 / _this.ratio)

			//矩形二维码
			_this.ctxCircular(ctx, _this.myObj.rwmImg, (305 / _this.ratio), (1200 / _this.ratio), (140 / _this.ratio),
				(140 / _this.ratio), 6)
			// 渲染画布
			ctx.draw(false, (() => {
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						destWidth: _this.canvasWidth * 2, //展示图片尺寸=画布尺寸1*像素比2
						destHeight: _this.canvasHeight * 2,
						quality: 1,
						fileType: 'jpg',
						success: (res) => {
							uni.hideLoading()
							console.log('通过画布绘制出的图片--保存的就是这个图', res.tempFilePath)
							_this.imgs = res.tempFilePath
							// _this.$refs.popup.open()
						},
						fail: function (error) {
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								position: 'bottom',
								title: "绘制图片失败", // res.tempFilePath
							})
						}
					}, _this)

				}, 100)
			})())
		},

	}
}
</script>
<style lang="scss">
.pop1 {
	background-color: #fff;
	width: 520rpx;
	padding: 68rpx 120rpx;
	box-sizing: border-box;
	border-radius: 20rpx;
	background: linear-gradient(#E6F5EB 45%, #FEFFFE 100%);

	.tit {
		font-size: 32rpx;
		color: #000000;
		margin: 20px 0px;
	}

	.btns {
		font-size: 32rpx;
		color: #fff;
		background-color: #00663A;
		border-radius: 14rpx;
		padding: 14rpx 30rpx;
		margin-top: 40rpx;
		text-align: center;
	}
}
</style>
